package 剑指offer_leetcode;

/**
 * JZ15二进制中1的个数
 */
public class 剑指Offer15_二进制中1的个数 {
    // you need to treat n as an unsigned value
    public int hammingWeight2(int n) {
        int res = 0;
        for(int i=0;i<32;i++){
            //按位比较
            if((n& (1<<i) )!=0)
                res++;
        }
        return res;
    }

    //n & (n-1)  会将n的二进制中最低位由 1 变为 0
    public int hammingWeight(int n) {
        int res= 0;
        while(n!=0){
            n &= (n-1);
            res++;
        }
        return res;
    }
}
